<template>
  <div class="app-container">
    <div class="page-card">
      <div class="page-form">
        <!-- <el-select
        v-model="queryParams.subjectiveType"
        placeholder="所在地区"
        clearable
        @change="handleSearch"
      >
      </el-select> -->
        <el-input
          v-model="queryParams.deptName"
          placeholder="学校/地区名称"
          clearable
          @input="handleSearch"
        />
        <el-input
          v-model="queryParams.schoolNumber"
          placeholder="学校代码"
          clearable
          @input="handleSearch"
        />
        <el-date-picker
          v-model="queryParams.createTime"
          type="date"
          placeholder="创建日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          clearable
          @change="handleSearch"
        >
        </el-date-picker>
      </div>

      <el-table
        stripe
        border
        v-if="refreshTable"
        v-loading="loading"
        :data="deptList"
        row-key="deptId"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column
          prop="deptName"
          label="学校/地区名称"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="学校代码"
          align="center"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope"
            >{{ scope.row.type == "1" ? scope.row.schoolNumber : "" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="schoolAlias"
          label="学校别名"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="学校邮箱"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="学段"
          align="center"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.school_segment_type"
              :value="scope.row.stage"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-link
              v-if="scope.row.level"
              type="primary"
              @click="handleAdd(scope.row)"
              v-hasRole="['admin']"
              >新增</el-link
            >
            <el-link
              v-if="scope.row.type == 1"
              type="primary"
              @click="gwks(scope.row)"
              >过往考试</el-link
            >
            <el-link type="primary" @click="handleUpdate(scope.row)"
              >编辑</el-link
            >
            <el-link
              type="danger"
              @click="handleDelete(scope.row)"
              v-if="scope.row.parentId != 0"
              v-hasRole="['admin']"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-bottom">
      <div class="sel-box">
        <el-button type="primary" @click="handleAdd" v-hasRole="['admin']"
          >新增</el-button
        >
        <el-button
          type="primary"
          @click="upload.open = true"
          v-hasRole="['admin']"
          >批量导入</el-button
        >
      </div>
    </div>

    <!-- 添加或修改学校对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="436px"
      class="editKmVisible"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-position="left"
        label-width="140px"
      >
        <el-row>
          <el-col :span="24" v-if="form.parentId">
            <el-form-item label="上级目录" prop="parentId">
              <el-cascader
                disabled
                v-model="form.parentId"
                :options="deptOptions"
                :props="{
                  label: 'deptName',
                  value: 'deptId',
                  emitPath: false,
                  checkStrictly: true,
                }"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item
              :label="`${form.level == 2 ? '学校' : '地区'}名称`"
              prop="deptName"
            >
              <el-input v-model="form.deptName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.level == 2">
          <el-col :span="24">
            <el-form-item label="学校别名" prop="schoolAlias">
              <el-input
                v-model="form.schoolAlias"
                placeholder="请输入学校名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.level == 2">
          <el-col :span="24">
            <el-form-item label="学校学段" prop="stage">
              <el-select v-model="form.stage" multiple>
                <el-option
                  v-for="dict in dict.type.school_segment_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="form.level == 2">
          <el-col :span="24">
            <el-form-item label="学校邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入学校邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number
                v-model="form.orderNum"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.level == 2">
          <el-col :span="12">
            <el-form-item label="学校状态">
              <el-radio-group v-model="form.status" style="width: 240px">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入 -->
    <el-dialog
      title="导入"
      :visible.sync="upload.open"
      :close-on-click-modal="false"
      width="400px"
      append-to-body
    >
      <!-- <el-select
        v-model="upload.parentId"
        placeholder="请选择地区"
        style="margin-bottom: 20px"
      >
        <el-option
          v-for="dict in dqList"
          :key="dict.deptId"
          :label="dict.deptName"
          :value="dict.deptId"
      /></el-select> -->
      <el-cascader
        style="margin-bottom: 15px"
        v-model="upload.parentId"
        :options="dqList"
        :props="{
          label: 'deptName',
          value: 'deptId',
          emitPath: false,
        }"
      ></el-cascader>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?parentId=' + upload.parentId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitFileForm"
          :loading="upload.isUploading"
          >确 定</el-button
        >
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 过往考试 -->
    <el-dialog title="过往考试" :visible.sync="gwksOpen">
      <el-table border stripe :data="gwksList">
        <el-table-column
          prop="examName"
          label="考试名称"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建日期"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click="
                dc(
                  '/system/exam/teacher/export',
                  { examId: scope.row.id, deptId: activeDeptId },
                  scope.row.examName + '_教师_'
                )
              "
              >导出教师信息</el-link
            >
            <el-link
              type="primary"
              @click="
                dc(
                  '/system/exam/student/export',
                  { examId: scope.row.id, schoolId: activeDeptId },
                  scope.row.examName + '_考生_'
                )
              "
              >导出学生信息</el-link
            ></template
          >
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
  listDeptExcludeChild,
} from "@/api/system/dept";
import { exammain } from "@/api/jcgl/xxgl";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import { debounce } from "lodash";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Basic_xxgl",
  dicts: ["sys_normal_disable", "school_segment_type"],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,

      // 所有数据
      allDeptList: null,
      // 表格树数据
      deptList: [],
      // 地区（二级）列表
      dqList: [],
      // 学校树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: undefined,
        schoolNumber: undefined,
        createTime: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deptName: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" },
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
      },

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 学校
        parentId: "",
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/dept/import",
      },

      gwksOpen: false,
      gwksList: [],
      activeDeptId: "",
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询学校列表 */
    getList() {
      if (!this.allDeptList) {
        this.loading = true;
        listDept(this.queryParams).then((response) => {
          // this.allDeptList = JSON.parse(JSON.stringify(response.data));
          this.deptList = this.handleTree(response.data, "deptId");
          console.log(this.deptList);
          let treeDeptList = JSON.parse(JSON.stringify(this.deptList));

          // 过滤出二级地区列表
          let dqList = JSON.parse(JSON.stringify(this.deptList)).filter(
            (item) => {
              return item.children && item.children.length > 0;
            }
          );
          dqList.map((item) => {
            item.children.map((v) => {
              delete v.children;
            });
          });
          this.dqList = dqList;

          let allDeptList = [];
          treeDeptList.map((item) => {
            item.parentDeptName = "";
            item.parentSchoolNumber = "";
            item.parentCreateTime = "";
            if (item.children) {
              item.children.map((item1) => {
                item1.parentDeptName = item1.deptName + "_" + item.deptName;
                item1.parentSchoolNumber =
                  item1.schoolNumber + "_" + item.schoolNumber;
                item1.parentCreateTime =
                  item1.createTime + "_" + item.createTime;
                if (item1.children) {
                  item1.children.map((item2) => {
                    item2.parentDeptName =
                      item2.deptName +
                      "_" +
                      item1.deptName +
                      "_" +
                      item.deptName;
                    item2.parentSchoolNumber =
                      item2.schoolNumber +
                      "_" +
                      item1.schoolNumber +
                      "_" +
                      item.schoolNumber;
                    item2.parentCreateTime =
                      item2.createTime +
                      "_" +
                      item1.createTime +
                      "_" +
                      item.createTime;
                    allDeptList.push(item2);
                  });
                }
                delete item1.children;
                allDeptList.push(item1);
              });
            }
            delete item.children;
            allDeptList.push(item);
          });

          this.allDeptList = allDeptList;

          this.loading = false;
        });
      } else {
        let deptList = [];
        deptList = JSON.parse(JSON.stringify(this.allDeptList)).filter(
          (item) => {
            let deptNameVerify = !this.queryParams.deptName
              ? true
              : item.deptName.indexOf(this.queryParams.deptName) != "-1" ||
                item.parentDeptName.indexOf(this.queryParams.deptName) != "-1";
            let schoolNumberVerify = !this.queryParams.schoolNumber
              ? true
              : item.schoolNumber.indexOf(this.queryParams.schoolNumber) !=
                  "-1" ||
                item.parentSchoolNumber.indexOf(
                  this.queryParams.schoolNumber
                ) != "-1";
            let createTimeVerify = !this.queryParams.createTime
              ? true
              : item.createTime.indexOf(this.queryParams.createTime) != "-1" ||
                item.parentCreateTime.indexOf(this.queryParams.createTime) !=
                  "-1";
            return deptNameVerify && schoolNumberVerify && createTimeVerify;
          }
        );
        this.deptList = this.handleTree(deptList, "deptId");
      }
    },
    /** 转换学校数据结构 */
    // normalizer(node) {
    //   if (node.children && !node.children.length) {
    //     delete node.children;
    //   }
    //   return {
    //     id: node.deptId,
    //     label: node.deptName,
    //     children: node.children,
    //   };
    // },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        stage: [],
        email: undefined,
        orderNum: undefined,
        status: "0",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.deptId;
      }
      this.open = true;
      this.form.level = row ? row.level : "";
      this.title = "新增";
      listDept().then((response) => {
        let deptOptions = this.handleTree(response.data, "deptId");
        deptOptions.map((item) => {
          if (item.children.length == 0) {
            delete item.children;
          } else {
            item.children.map((v) => {
              delete v.children;
            });
          }
        });
        this.deptOptions = deptOptions;
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getDept(row.deptId).then((response) => {
        this.form = {
          ...response.data,
          stage: response.data.stage ? response.data.stage.split(",") : [],
          level: row.type != 1 ? row.level - 1 : 2,
        };
        this.open = true;
        this.title = "编辑";
        listDeptExcludeChild(row.deptId).then((response) => {
          let deptOptions = this.handleTree(response.data, "deptId");
          deptOptions.map((item) => {
            if (item.children.length == 0) {
              delete item.children;
            } else {
              item.children.map((v) => {
                delete v.children;
              });
            }
          });
          this.deptOptions = deptOptions;

          if (this.deptOptions.length == 0) {
            const noResultsOptions = {
              deptId: this.form.parentId,
              deptName: this.form.parentName,
              children: [],
            };
            this.deptOptions.push(noResultsOptions);
          }
        });
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let data = { ...this.form, stage: this.form.stage.join(",") };
          // type==1 代表是学校
          data.type = "0";
          if (this.form.level == 2) {
            data.type = "1";
          }
          if (this.form.deptId != undefined) {
            updateDept(data).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.allDeptList = null;
              this.getList();
            });
          } else {
            addDept(data).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.allDeptList = null;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.deptName + '"的数据项？')
        .then(function () {
          return delDept(row.deptId);
        })
        .then(() => {
          this.allDeptList = null;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    debouncedSearch: debounce(function () {
      this.queryParams.pageNum = 1;
      this.getList();
    }, 500),

    handleSearch() {
      this.debouncedSearch();
    },

    gwks(row) {
      this.loading = true;
      exammain({
        schoolId: row.deptId,
      })
        .then((res) => {
          this.activeDeptId = row.deptId;
          this.gwksList = res.data;
          this.gwksOpen = true;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    dc(url, data, name) {
      this.download(url, data, `${name}${new Date().getTime()}.xlsx`);
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      window.open(
        "https://bs-exam-bucket.oss-cn-beijing.aliyuncs.com/dev/bsta/exam/uploadPath/upload/template/base_school_template.xlsx"
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.parentId = "";
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.allDeptList = null;
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      if (!this.upload.parentId) {
        this.$modal.alertError("请选择导入地区");
        return;
      }
      this.$refs.upload.submit();
    },
  },
};
</script>

<style lang="scss" scoped>
.editKmVisible {
  .vue-treeselect,
  .el-cascader,
  .el-input,
  .el-select {
    width: 240px;
  }
}
</style>
